<template>
	<image :src="img_url" :mode="mode" :lazy-load="lazyLoad" :style="setStyle"></image>
</template>

<script>
import { pathToBase64 } from '../../js_sdk/gsq-image-tools/image-tools';
export default {
	name: 'image-cache',
	props: {
		mode: {
			type: String,
			default: ''
		},
		lazyLoad: {
			type: Boolean,
			default: false
		},
		imgSrc: {
			type: String
		},
		defaultImg: {
			type: String,
			default: ''
		},
		setStyle: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			img_url: ''
		};
	},
	mounted() {
		this.imgUrl();
	},
	updated() {
		this.imgUrl();
	},
	methods: {
		imgUrl() {
			uni.getStorage({
				key: this.imgSrc,
				success: res => {
					if (res.data != '') {
						this.img_url = res.data;
					} else {
						uni.downloadFile({
							url: this.imgSrc,
							success: async ress => {
								if (ress.statusCode === 200) {
									let imgData = await pathToBase64(ress.tempFilePath);
									console.log(imgData);
									uni.setStorage({
										key: this.imgSrc,
										data: imgData,
										success: function() {}
									});
									this.img_url = imgData;
								} else {
									this.img_url = this.defaultImg;
								}
							},
							fail: () => {
								this.img_url = this.defaultImg;
							}
						});
					}
				},
				fail: res => {
					uni.downloadFile({
						url: this.imgSrc,
						success: async ress => {
							if (ress.statusCode === 200) {
								let imgData = await pathToBase64(ress.tempFilePath);
								uni.setStorage({
									key: this.imgSrc,
									data: imgData,
									success: function() {}
								});
								this.img_url = imgData;
							} else {
								this.img_url = this.defaultImg;
							}
						},
						fail: () => {
							this.img_url = this.defaultImg;
						}
					});
				}
			});
		}
	}
};
</script>
